package com.breeze.blockchain.auth;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.strategy.SaStrategy;
import com.breeze.blockchain.auth.util.AdminUserUtil;
import com.breeze.blockchain.auth.util.AppUserUtil;
import com.breeze.blockchain.common.interceptor.UserContextInterceptor;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * sa token支持
 *
 * @author breeze
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

  @Resource UserContextInterceptor userContextInterceptor;

  @Bean
  public StpLogic getStpLogicJwt() {
    return new StpLogicJwtForSimple();
  }

  @PostConstruct
  public void configSaToken() {
    // 重写Sa-Token的注解处理器，增加注解合并功能
    SaStrategy.instance.getAnnotation = AnnotatedElementUtils::getMergedAnnotation;
    AdminUserUtil.stpLogic.setConfig(
        new SaTokenConfig()
            .setTokenName("Authorization")
            .setTimeout(24 * 60 * 60)
            .setActiveTimeout(-1)
            .setIsConcurrent(true)
            .setIsReadCookie(false)
            .setIsShare(true)
            .setIsLog(false)
            .setIsPrint(false)
            .setJwtSecretKey("adminqweasdas"));
    AppUserUtil.stpLogic.setConfig(
        new SaTokenConfig()
            .setTokenName("Authorization")
            .setTimeout(7 * 24 * 60 * 60)
            .setActiveTimeout(-1)
            .setIsConcurrent(true)
            .setIsReadCookie(false)
            .setIsShare(true)
            .setIsLog(false)
            .setIsPrint(false)
            .setJwtSecretKey("appdsanjnqwqe"));
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(userContextInterceptor).addPathPatterns("/**");
    registry
        .addInterceptor(
            new SaInterceptor(
                handler -> {
                  // app
                  SaRouter.match("/api/app/**")
                      .notMatch("/api/app/login")
                      .notMatch("/api/app/public/**")
                      .check(r -> AppUserUtil.checkLogin());

                  // admin
                  SaRouter.match("/api/admin/**")
                      .notMatch("/api/admin/login")
                      .notMatch("/api/admin/public/**")
                      .check(r -> AdminUserUtil.checkLogin());
                }))
        .addPathPatterns("/**");
  }
}
